package net.gz01.wallet.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

import net.gz01.wallet.common.LayuiRespon;
import net.gz01.wallet.common.ZOPage;
import net.gz01.wallet.common.ZOSearchCondition;

public class BaseController extends Controller{

	/**
	 * 获取查询对象 <br/>
	 * 会将请求的所有  key=value  封装到ESSearchCondition中
	 * @return
	 */
	protected ZOSearchCondition getSearchCondition() {
		Map<String, String[]> temp = getParaMap();
		ZOSearchCondition sc = new ZOSearchCondition();
		Set<String> keys = temp.keySet();
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			String key = (String) it.next();
			String value = temp.get(key)[0].trim();
			if (StrKit.notBlank(value)) {
				sc.getParameters().put(key, value);
				setAttr(key, value);
			}
		}
		sc.page.setPageNum(getParaToInt("page"));
		sc.page.setNumPerPage(getParaToInt("limit"));
		return sc;
	}

	@Override
	public void render(String view) {
		String path = getRequest().getContextPath();
		String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+path+"/";
		setAttr("basePath", basePath);
		setAttr("session", getRequest().getSession());
		super.render(view);
	}

	public String getStringFromRequest(){
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(getRequest().getInputStream(),"UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String string;
			while((string = reader.readLine()) != null){
				buffer.append(string);
			}
			String parameterString = URLDecoder.decode(buffer.toString(),"UTF-8");
			return parameterString;

		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 设置结果
	 * @param listName  集合的名字
	 * @param pageResult  分页结果集
	 */
	public void setPageResultToRequest(String listName,Page<? extends Model<?>> pageResult) {
		setAttr(listName, pageResult.getList());
		ZOPage page = new ZOPage();
		page.setPageNum(pageResult.getPageNumber());
		page.setNumPerPage(pageResult.getPageSize());
		page.setTotal(pageResult.getTotalRow());
		setAttr("page", page);
	}


	protected void renderStream(String file) {
		renderStream(new File(file));
	}

	/**
	 * 返回图片流
	 * @param imageFile
	 */
	protected void renderStream(File imageFile) {
		HttpServletResponse response = getResponse();
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);

		InputStream is = null;
		byte[] content = new byte[131072];	// 128k
		int len = 0;
		try {
			ServletOutputStream sos = response.getOutputStream();
			is = new BufferedInputStream(new FileInputStream(imageFile));
			do{
				sos.write(content, 0, len);
				len = is.read(content);
			}while(len!=-1);
				sos.flush();
				is.close();
				sos.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
		renderNull();
	}

	//------------------------------- DWZ AJAX 响应 --------------------------------

	public void renderSuccess() {
		renderSuccess(null, true);
	}

	public void renderSuccess(String message) {
		renderSuccess(message, true);
	}

	public void renderSuccess(String message, Map<String, Object> data){
		renderLayuiJson(0, message, data);
	}


	/**
	 *
	 * @param closeCurrent 是否关闭当前打开navTab或dialog
	 */
	public void renderSuccess(boolean closeCurrent) {
		renderSuccess(null, closeCurrent);
	}

	public void renderSuccess(String message,boolean closeCurrent) {
		//renderDWZJson("200", message, closeCurrent);
		renderLayuiJson(0, message);
	}

	/**
	 * 失败的默认是不关闭当前打开页面
	 */
	public void renderFail() {
		renderFail(null, false);
	}

	/**
	 * 失败的默认是不关闭当前打开页面
	 */
	public void renderFail(String message) {
		renderFail(message, false);
	}


	/**
	 * 失败的默认是不关闭当前打开页面
	 */
	public void renderMsg(int code, String message) {
		renderLayuiJson(code, message);
	}

	/**
	 * 失败的默认是不关闭当前打开页面
	 */
	public void renderFail(boolean closeCurrent) {
		renderFail(null, closeCurrent);
	}

	/**
	 * 失败的默认是不关闭当前打开页面
	 */
	public void renderFail(String message,boolean closeCurrent) {
		//renderDWZJson("300", message, closeCurrent);
		renderLayuiJson(300, message);
	}

	private void renderLayuiJson(int statusCode,String message) {
		LayuiRespon rsp = new LayuiRespon();
		rsp.setCode(statusCode);
		if(StrKit.notBlank(message)) {
			rsp.setMsg(message);
		}
		renderJson(rsp);
	}


	private void renderLayuiJson(int statusCode,String message, Map<String, Object> data) {
		LayuiRespon rsp = new LayuiRespon();
		rsp.setCode(statusCode);
		if(StrKit.notBlank(message)) {
			rsp.setMsg(message);
		}
		if(data!=null){
			rsp.setData(data);
		}
		renderJson(rsp);
	}

}
